package com.breakfast.fun.adapter.user;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.breakfast.fun.R;
import com.breakfast.fun.base.BaseListAdapter;
import com.breakfast.fun.dao.DaoMaster;
import com.breakfast.fun.dao.ProductCart;
import com.breakfast.fun.dao.ProductCartDao;
import com.breakfast.fun.event.CartEvent;
import com.breakfast.fun.util.DaoUtil;
import com.breakfast.fun.util.L;
import com.breakfast.fun.util.PopUtil;
import com.breakfast.fun.util.T;
import com.breakfast.fun.util.TimeUtil;
import com.breakfast.fun.view.widget.PurchaseButton;
import com.breakfast.fun.view.widget.WheelPicker;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

import static com.breakfast.fun.util.DaoUtil.getProductList;


/**
 * Created by yukai on 16/9/16.
 */
public class CartProductAdapter extends BaseListAdapter<ProductCart> {


    private ProductCartDao mProductCartDao;

    private List<ProductCart> productCarts;
    private int totalNum = 0;
    private double totalPrice = 0;
    private CartEvent event = new CartEvent();
    private List<String> canBuyList;

    private Context mContext;
    public addClickListener mAddClick;

    public interface addClickListener {
        public void add(View view);
    }

    public void setAddClickListener(addClickListener addClick) {
        mAddClick = addClick;
    }

    public CartProductAdapter(Context context, List<ProductCart> list, List<String> canBuyList) {
        super(context, list);
        mContext = context;
        this.canBuyList = canBuyList;
        mProductCartDao = DaoMaster.newDevSession(context, "zaofan.db").getProductCartDao();
        productCarts = mProductCartDao.loadAll();
        for (int i = 0; i < productCarts.size(); i++) {
            totalPrice += productCarts.get(i).getTotalPrice();
            totalNum += productCarts.get(i).getNum();

        }
        event.setTotalPrice(totalPrice);
        event.setTotalNum(totalNum);
        EventBus.getDefault().post(event);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_cart_product, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        ProductCart data = getItem(position);

        holder.mTvCartProductPrice.setText("￥" + data.getPrice() + "/份");
        holder.mTvCartProductName.setText(data.getName());
        holder.mTvCartProductCount.setText(data.getNum() + "");


        holder.mTvCartSendDate.setText(data.getDate() + " [" +
                TimeUtil.CalcuDate(data.getDate()) + "]");

        holder.mBtnCartProductAdd.setOnClickListener(v -> {
            holder.mTvCartProductCount.setText(Integer.parseInt(holder.mTvCartProductCount.getText().toString()) + 1 + "");
            addProduct(data, holder);
            if (mAddClick != null) {
                mAddClick.add(holder.mBtnCartProductAdd);
            }
        });

        holder.mBtnCartProductDel.setOnClickListener(v -> {
            delProduct(data, holder);
        });

        holder.mRlCartItemDate.setOnClickListener(v -> {
            showSendDate(holder, data);
        });

        imageUtil.loadUrlImage(data.getImage(), holder.mIvCartProduct);
        return convertView;
    }

    private void showSendDate(ViewHolder holder, ProductCart data) {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.widget_pop_picker, null);

        TextView tvWheelpickerCancel = (TextView) contentView.findViewById(R.id.tv_wheelpicker_cancel);
        TextView tvWheelpickerOk = (TextView) contentView.findViewById(R.id.tv_wheelpicker_ok);
        final WheelPicker wpWheelPicker = (WheelPicker) contentView.findViewById(R.id.wp_wheelpicker);
        wpWheelPicker.setData(canBuyList);
        final PopupWindow popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        PopUtil.setPop(popupWindow);

        tvWheelpickerOk.setOnClickListener(v -> {
            if (wpWheelPicker.getData().size() <= wpWheelPicker.getCurrentItemPosition()) {
                T.show("设置日期失败");
                popupWindow.dismiss();
                return;
            }
            String sendDate = (String) wpWheelPicker.getData().get(wpWheelPicker.getCurrentItemPosition());
            holder.mTvCartSendDate.setText(sendDate);
            data.setDate(sendDate.substring(0, sendDate.length() - 5));
            mProductCartDao.update(data);
            popupWindow.dismiss();
        });

        tvWheelpickerCancel.setOnClickListener(v -> {
            popupWindow.dismiss();
        });

        EventBus.getDefault().post(popupWindow);
    }

    private void delProduct(ProductCart data, ViewHolder holder) {
        List<ProductCart> productCartList = DaoUtil.getProductList(data.getCategoryId(), data.getProductId(), data.getDate());

        data.setNum(productCartList.get(0).getNum() - 1);

        productCartList.get(0).setNum(productCartList.get(0).getNum() - 1);
        productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
        mProductCartDao.update(productCartList.get(0));
        holder.mTvCartProductCount.setText(productCartList.get(0).getNum() + "");
        totalNum -= 1;
        totalPrice -= data.getPrice();
        event.setTotalNum(totalNum);
        event.setTotalPrice(totalPrice);
        EventBus.getDefault().post(event);

        if (productCartList.get(0).getNum() == 0) {
            mProductCartDao.delete(productCartList.get(0));
            removeEntity(data);
            notifyDataSetChanged();
        }
    }

    private void addProduct(ProductCart data, ViewHolder holder) {
        if (data.getProductClassId().equals("19")) {
            T.show("该商品仅限一份");
            return;
        }
        List<ProductCart> productCartList = getProductList(data.getCategoryId(), data.getProductId(), data.getDate());
        holder.mTvCartProductCount.setText(productCartList.get(0).getNum() + 1 + "");
        data.setNum(productCartList.get(0).getNum() + 1);

        productCartList.get(0).setNum(productCartList.get(0).getNum() + 1);
        productCartList.get(0).setTotalPrice(productCartList.get(0).getPrice() * productCartList.get(0).getNum());
        mProductCartDao.update(productCartList.get(0));

        totalNum += 1;
        totalPrice += data.getPrice();
        event.setTotalNum(totalNum);
        event.setTotalPrice(totalPrice);
        EventBus.getDefault().post(event);


    }


    static class ViewHolder {
        @Bind(R.id.tv_cart_item_date_hint)
        TextView mTvCartItemDateHint;
        @Bind(R.id.tv_cart_send_date)
        TextView mTvCartSendDate;
        @Bind(R.id.rl_cart_item_date)
        RelativeLayout mRlCartItemDate;
        @Bind(R.id.iv_cart_product)
        ImageView mIvCartProduct;
        @Bind(R.id.tv_cart_product_name)
        TextView mTvCartProductName;
        @Bind(R.id.tv_cart_product_price)
        TextView mTvCartProductPrice;
        @Bind(R.id.btn_cart_product_add)
        Button mBtnCartProductAdd;
        @Bind(R.id.tv_cart_product_count)
        TextView mTvCartProductCount;
        @Bind(R.id.btn_cart_product_del)
        Button mBtnCartProductDel;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
